package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.bean.actsnapup;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.lockorder.LockOrderInfo;
import yxy.game.pm2.active.module.subordinateclass.FlashSale;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 限时抢购  7天刷新一次
 * @author Dell
 */
public class ActiveModule_限时抢购 extends PlayerModule {

	//bean ------------------------------------------------------

	public static final int acttype = 7;
	
	private DateTime refreshtime;	//刷新时间
	private ArrayList<FlashSale> fss = new ArrayList<FlashSale>();
	
	public DateTime getRefreshtime() {
		return refreshtime;
	}
	public void setRefreshtime(DateTime refreshtime) {
		this.refreshtime = refreshtime;
	}
	public ArrayList<FlashSale> getFss() {
		return fss;
	}
	public void setFss(ArrayList<FlashSale> fss) {
		this.fss = fss;
	}

	// func -----------------------------------------------------------

	public static final int canget = 1;
	public static final int hadget = 2;
	public static final int cannotget = 3;
	
	/**
	 * @param pcode
	 */
	public static ActiveModule_限时抢购 create(String pcode) {
		PlayerBean pb = PlayerBean.get(pcode);
		int sid = pb.getServerId();

		ServerBean sb = ServerBean.get(sid);
		int areaid = sb.getAreaId();

//		DateTime now = DateTime.now();
		DateTime refreshtime = ActiveUtil.time0();
		activeControl sai = activeControl.get(areaid, acttype);
		if (sai != null) {
			ActiveModule_限时抢购 am = new ActiveModule_限时抢购();
			am.setPlayerCode(pcode);
			am.setRefreshtime(refreshtime);
			am.setTimeline(sai.getTimeline());
			
			Map<String, actsnapup> aspmap = ActDataCenter.getAllData(actsnapup.class, pcode);
			for(String key : aspmap.keySet()) {
				actsnapup asp = aspmap.get(key);
				FlashSale fs = new FlashSale();
//				ArrayList<Currency> curs = (ArrayList<Currency>) Currency.create(asp.getRewardtype(), asp.getRewardid(), asp.getRewardnum());
				
				fs.setId(asp.getId());
				fs.setGoodsid(asp.getPurchasever());
				fs.setBuylimitnum(asp.getLimit());
				fs.setPakename(asp.getPakename());
				fs.setBuynum(0);
//				fs.setCurs(curs);
				
				am.getFss().add(fs);
			}
			
			am.set();
			return am;
		}

		return null;
	}

	public void update() {
		PlayerBean pb = PlayerBean.get(getPlayerCode());
		ServerBean sb = ServerBean.get(pb.getServerId());
		activeControl sai = activeControl.get(String.valueOf(sb.getAreaId()), String.valueOf(acttype));
		if(sai == null) {
			return;
		}
		
		if(ActiveUtil.days0(getRefreshtime(), DateTime.now()) > 7) {
			refresh(sai);
			set();
		}
		
		// 关闭活动
		if (!sai.running() && running()) {
			setTimeline(sai.getTimeline());
			set();
		}

		// 开启活动
		if (sai.running() && !running()) {
			refresh(sai);
			set();
		}
		
		boolean save = false;
		DateTime now = DateTime.now();
		for (FlashSale fs : getFss()) {
			ArrayList<String> removekeys = new ArrayList<String>();
			Set<String> keys = fs.getOrderidtimemap().keySet();
			for (String key : keys) {
				long times = now.getMillis() - fs.getOrderidtimemap().get(key).getMillis();
				if (times > LockOrderInfo.lockTime()) {
					removekeys.add(key);
					save = true;
				}
			}
			
			for(String removekey : removekeys) {
				fs.getOrderidtimemap().remove(removekey);
			}
		}
		
		if(save) {
			set();
		}

	}

	/**
	 * 锁单
	 * @param goodsid
	 * @param orderid
	 */
	public void lockOrder(int goodsid, String orderid) {
		for(FlashSale fs : getFss()) {
			if(fs.getGoodsid() == goodsid) {
				fs.getOrderidtimemap().put(orderid, DateTime.now());
				set();
				return;
			}
		}
	}
	
	/**
	 * 订单完成 解除锁单
	 * @param goodsid
	 * @param orderid
	 */
	public void orderFinish(int goodsid, String orderid) {
		for(FlashSale fs : getFss()) {
			if(fs.getGoodsid() == goodsid) {
				int buynum = fs.getBuynum();
				buynum++;
				fs.setBuynum(buynum);
				fs.getOrderidtimemap().remove(orderid);
				set();
				return;
			}
		}
	}
	
	public void refresh(activeControl sai) {
		setRefreshtime(DateTime.now());
		setTimeline(sai.getTimeline());
		setFss(new ArrayList<FlashSale>());
		
		Map<String, actsnapup> aspmap = ActDataCenter.getAllData(actsnapup.class, getPlayerCode());
		for (String key : aspmap.keySet()) {
			actsnapup asp = aspmap.get(key);
			FlashSale fs = new FlashSale();
//			ArrayList<Currency> curs = (ArrayList<Currency>) Currency.create(asp.getRewardtype(), asp.getRewardid(), asp.getRewardnum());

			fs.setId(asp.getId());
			fs.setGoodsid(asp.getPurchasever());
			fs.setBuylimitnum(asp.getLimit());
			fs.setPakename(asp.getPakename());
			fs.setBuynum(0);
//			fs.setCurs(curs);
			fs.setOrderidtimemap(new HashMap<String, DateTime>());

			getFss().add(fs);
		}
	}
	
	
	// redis ---------------------------------------------------------

	static private String key(String playerCode) {
		return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
	}

	public void set() {
		try {
			String key1 = key(getPlayerCode());
			setv(key1, this);
			check();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取 ActiveModule_限时抢购
	 * @param playerCode
	 * @return
	 */
	static public ActiveModule_限时抢购 get(String playerCode, Boolean isNewPlayer) {
		try {
			ActiveModule_限时抢购 module = getv(key(playerCode));

			//新用户不需要去查数据库
			if (module == null && !isNewPlayer) {
				module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_限时抢购.class);
				if(module != null){module.set();}//同步到redis
			}

			if(module != null){
				int size = ActDataCenter.getAllData(actsnapup.class, playerCode).size();
				if (module.getFss().size() != size){
					ArrayList<Integer> ids = new ArrayList<>();
					ArrayList<FlashSale> fss = module.getFss();
					for (int i = 0; i < fss.size(); i++) {
						ids.add(module.getFss().get(i).getGoodsid());
					}
					for (actsnapup value : ActDataCenter.getAllData(actsnapup.class, playerCode).values()) {
						if (!ids.contains(value.getPurchasever())){
							FlashSale fs = new FlashSale();

							fs.setId(value.getId());
							fs.setGoodsid(value.getPurchasever());
							fs.setBuylimitnum(value.getLimit());
							fs.setPakename(value.getPakename());
							fs.setBuynum(0);

							fss.add(fs);
						}
					}
					module.setFss(fss);
					module.set();
				}
			}

			if (module == null) {
				module = create(playerCode);
			}
			if(module == null){return null;}

			module.update();
			module.check();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/** 查看是否有可领取奖励 控制红点 */
	public void check() {
		if (running()) {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
		} else {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
		}
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				ActiveModule_限时抢购 activeModule_限时抢购 = getv(key(playerCode));
				MySQLCacheDAO.setV(key, activeModule_限时抢购);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}

}
